package com.daykw.douyin.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoAuth;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoExtUserThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoExtUserThread.class);

	@Override
	public void run() {

		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		List<VideoAuth> auths = dao.query(VideoAuth.class,
				// Cnd.where("ext_info", "is not", null).and("ext_fans", "is",
				// null).desc("follower_num"));
				Cnd.where("ext_user", "is", null).and("kw_uid", "is not", null).limit(1, 10).desc("follower_num"));

		for (VideoAuth task : auths) {
			try {

				this.doWork(task);

			} catch (Exception e) {
				logger.error("", e);
			}
		}

	}

	private void doWork(VideoAuth task) {
		try {
			NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			List<Record> cookies = dao.query("t_cookie", Cnd.wrap("WHERE auth_status=1 "));

			headers.put("Host", "dsp.feigua.cn");
			headers.put("Referer", "https://dy.feigua.cn/Member");
			headers.put("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
			int random = org.apache.commons.lang3.RandomUtils.nextInt(0, cookies.size());

			Record cookie = cookies.get(random);
			String cname = cookie.getString("name");
			String c = cookie.getString("cookie");
			headers.put("Cookie", c);
			String html = http.get("https://dy.feigua.cn/Blogger/FansAnalysis?uid=" + task.getKw_uid(), headers);

			Document doc = Jsoup.parse(html);

			JSONObject json = new JSONObject();

			JSONArray sexArr = new JSONArray();
			Elements ges = doc.select("div.gender-text div.col-sm-6");
			for (Element s : ges) {
				JSONObject sjson = new JSONObject();
				String val = s.text();
				if (val.indexOf("男") >= 0) {
					String[] sexs = val.split(" ");
					sjson.put("sex", sexs[0]);
					sjson.put("val", sexs[1]);
				} else {
					String[] sexs = val.split(" ");
					sjson.put("sex", sexs[0]);
					sjson.put("val", sexs[1]);
				}
				sexArr.add(sjson);
			}
			json.put("sex", sexArr);

			JSONArray areaArr = new JSONArray();
			Elements trs = doc.select("table.location-table tr");
			for (Element tr : trs) {
				JSONObject ajson = new JSONObject();
				Elements tds = tr.select("td");

				ajson.put("area", tds.get(0).text());
				ajson.put("val", tds.get(1).text());
				areaArr.add(ajson);

			}
			json.put("area", areaArr);

			Elements scripts = doc.getElementsByTag("script");

			String age_data = null;
			for (Element s : scripts) {

				String script = s.toString();
				if (script.indexOf("age_data") > 0) {
					String[] sc = script.split("\r\n");

					for (String row : sc) {
						if (row.indexOf("age_data") > 0) {

							age_data = row.substring(row.indexOf("["), row.lastIndexOf("]") + 1);

							break;
						}

					}

				}
			}

			if (StringUtils.isNotEmpty(age_data)) {
				JSONArray age_data_arry = JSONArray.parseArray(age_data);
				json.put("age_data", age_data_arry);
			} else {
				json.put("age_data", new JSONArray());
			}

			if (json.getJSONArray("age_data").size() > 0 || json.getJSONArray("sex").size() > 0
					|| json.getJSONArray("area").size() > 0) {
				dao.update(VideoAuth.class, Chain.make("ext_user", json.toJSONString()),
						Cnd.where("id", "=", task.getId()));

			} else {
				logger.info("id:" + task.getId() + "获取其他信息为空");

			}

			logger.info("下载完用户其他个人信息完毕：" + task.getKw_uid());
		} catch (Exception e) {
			logger.error("", e);
		}

	}
}
